﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;

/// <summary>
/// 生成BLL层
/// </summary>
internal class CAutoBLL
{
    #region BLL

    /// <summary>
    /// 生成业务
    /// </summary>
    /// <param name="db_name"> 数据库名 </param>
    /// <param name="tablename"> 表名 </param>
    /// <param name="db"></param>
    /// <returns></returns>
    public static string CreateBLL(string db_name, string tablename, CDatabase db)
    {
        string str_namespace = Cconst.DefaultNameSpace;         // 默认命名空间
        string auther = Cconst.DefaultAuther;                   // 默认作者

        return CreateBLL(db_name, tablename, str_namespace, auther, db);
    }

    /// <summary>
    /// 生成业务
    /// </summary>
    /// <param name="db_name"> 数据库名 </param>
    /// <param name="tablename"> 表名 </param>
    /// <param name="str_namespace"> 命名空间 </param>
    /// <param name="db"></param>
    /// <returns></returns>
    public static string CreateBLL(string db_name, string tablename, string str_namespace, string auther, CDatabase db)
    {
        if (str_namespace == "")
            str_namespace = Cconst.DefaultNameSpace;         // 默认命名空间

        if (auther == "")
            auther = Cconst.DefaultAuther;                   // 默认作者

        // 新建目录
        string fileName = CUtility.GetTableName(tablename);
        string directoryPath = CUtility.GetBaseDirectory() + db_name + "\\BLL\\";
        bool exists = CFile.CreateDirectory(directoryPath);

        // 添加文件
        string filePath = CUtility.GetBaseDirectory() + db_name + "\\BLL\\" + fileName + "BLL.cs";

        string keyName = CUtility.GetKeyNameByTableName(tablename, db);
        string fieldsname = "";         // 如: int id, string name, string namePy...
        string parmname = "";           // 如: parms.Add(new SqlParameter("@id",id));\rparms.Add(new SqlParameter("@name",name));... 

        if (exists)
        {
            string p_listName = "p_" + tablename.Replace("t_", "").Replace("T_", "") + "_list";
            string p_saveName = "p_" + tablename.Replace("t_", "").Replace("T_", "") + "_save";
            string p_detailName = "p_" + tablename.Replace("t_", "").Replace("T_", "") + "_detail";
            string p_deleteName = "p_" + tablename.Replace("t_", "").Replace("T_", "") + "_delete";

            StreamWriter w = new StreamWriter(filePath, true, Encoding.Default);
            w.WriteLine(@"/*======================================*\");
            w.WriteLine("* Author: " + auther);
            w.WriteLine("* LastModifyUser: " + auther);
            w.WriteLine("* Description: ");
            w.WriteLine("* FileName：" + fileName + "BLL");
            w.WriteLine("* CreateTime： " + DateTime.Now.ToString());
            w.WriteLine("* Remark: 业务层");
            w.WriteLine(@"\*======================================*/");

            w.WriteLine("using System;");
            w.WriteLine("using System.Text;");
            w.WriteLine("using System.Data;");
            w.WriteLine("using System.Data.SqlClient;");
            w.WriteLine("using System.Collections.Generic;\r");
            w.WriteLine("namespace " + str_namespace + "\r{");
            w.WriteLine("   public class " + fileName + "BLL\r   {");

            #region 公用方法
            w.WriteLine("       #region 公用方法");

            #region 查询

            // p_tablename_list 返回 list 数据
            w.WriteLine("       /// <summary>");
            w.WriteLine("       /// 分页查询");
            w.WriteLine("       /// </summary>");
            w.WriteLine("       /// <param name=\"page\">当前页</param>");
            w.WriteLine("       /// <param name=\"pagesize\">每页显示多少</param>");
            w.WriteLine("       /// <param name=\"condition\">查询条件, 如 \" where 1=1 and id=222\"</param>");                        
            w.WriteLine("       /// <returns>返回List实体</returns>");
            w.WriteLine("       public static List<" + fileName + "Entity> " + p_listName + "(int page, int pagesize, string condition)");
            w.WriteLine("       {");
            w.WriteLine("           int total = 0;");
            w.WriteLine("           return " + fileName + "DAL." + p_listName + "(page, pagesize, condition, ref total);");            
            w.WriteLine("       }\r");

            // p_tablename_list 返回 DataTable 数据     
            w.WriteLine("       /// <summary>");
            w.WriteLine("       /// 分页查询");
            w.WriteLine("       /// </summary>");
            w.WriteLine("       /// <param name=\"page\">当前页</param>");
            w.WriteLine("       /// <param name=\"pagesize\">每页显示多少</param>");
            w.WriteLine("       /// <param name=\"condition\">查询条件, 如 \" where 1=1 and id=222\"</param>");                    
            w.WriteLine("       /// <returns>返回DataTable</returns>");       
            w.WriteLine("       public static DataTable " + p_listName + "_table(int page, int pagesize, string condition)");
            w.WriteLine("       {");
            w.WriteLine("           int total = 0;");            
            w.WriteLine("           return " + fileName + "DAL." + p_listName + "_table(page, pagesize, condition, ref total);");            
            w.WriteLine("       }\r");

            // p_tablename_list 返回 json 数据
            w.WriteLine("       /// <summary>");
            w.WriteLine("       /// 分页查询");
            w.WriteLine("       /// </summary>");
            w.WriteLine("       /// <param name=\"page\">当前页</param>");
            w.WriteLine("       /// <param name=\"pagesize\">每页显示多少</param>");
            w.WriteLine("       /// <param name=\"condition\">查询条件, 如 \" where 1=1 and id=222\"</param>");
            w.WriteLine("       /// <returns>返回Json数据</returns>");   
            w.WriteLine("       public static string " + p_listName + "_json(int page, int pagesize, string condition)");
            w.WriteLine("       {");
            w.WriteLine("           int total = 0;           // 总记录数");
            w.WriteLine("           int pageall = 0;         // 总页数\r");
            w.WriteLine("           DataTable dt = null;");            
            w.WriteLine("           dt = " + fileName + "DAL." + p_listName + "_table(page, pagesize, condition, ref total);");            
            w.WriteLine("           pageall = _Utility.GetPageAll(pagesize, total);      // 总页数");
            w.WriteLine("           _Json json = new _Json(dt);");
            w.WriteLine("           return \"{page:{currentpage:'\" + page + \"',pagesize:'\" + pagesize + \"',total:'\" + total + \"',pageall:'\" + pageall + \"'},record:\" + json.ToJson() + \"}\";");
            w.WriteLine("       }\r");
            
            // p_tablename_detail方法,返回实体     
            string sql = "select name,type_name(xusertype)as typename,isoutparam from syscolumns where id = object_id('" + p_detailName + "')";
            DataTable dt_proce_columns = db.ExecuteSql(sql);    // 过程的所有参数

            if (dt_proce_columns != null && dt_proce_columns.Rows.Count > 0)
            {
                fieldsname = "";
                parmname = "";
                for (int j = 0; j < dt_proce_columns.Rows.Count; j++)
                {
                    int isoutparam = 0;
                    try
                    {
                        isoutparam = Convert.ToInt32(dt_proce_columns.Rows[j]["isoutparam"].ToString());
                    }
                    catch { }

                    if (isoutparam == 0)
                    {
                        fieldsname += CUtility.SqlDataTypeToCodeType(dt_proce_columns.Rows[j]["typename"].ToString()) + " " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");

                        parmname += dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                    }
                    else
                    {
                        //fieldsname += "out " + CUtility.SqlDataTypeToCodeType(dt_proce_columns.Rows[j]["typename"].ToString()) + " " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                        parmname += " ref " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                    }

                    if (j < dt_proce_columns.Rows.Count - 1)
                    {
                        fieldsname += ",";
                        parmname += ",";
                    }
                }
                w.WriteLine("       /// <summary>");
                w.WriteLine("       /// 查询详情,返回实体");
                w.WriteLine("       /// </summary>");
                w.WriteLine("       public static " + fileName + "Entity " + p_detailName + "(" + fieldsname + ")");
                w.WriteLine("       {");                
                w.WriteLine("           return " + fileName + "DAL." + p_detailName + "(" + parmname + ");");                
                w.WriteLine("       }\r");


                // p_tablename_detail_json方法,返回 json数据
                w.WriteLine("       /// <summary>");
                w.WriteLine("       /// 查询详情,返回json数据");
                w.WriteLine("       /// </summary>");
                w.WriteLine("       public static string " + p_detailName + "_json(" + fieldsname + ")");
                w.WriteLine("       {");
                w.WriteLine("           DataTable dt = null;");                
                w.WriteLine("           dt = " + fileName + "DAL." + p_detailName + "_table(" + parmname + ");");                
                w.WriteLine("           _Json json = new _Json(dt);");
                w.WriteLine("           return \"{record:\" + json.ToJson() + \"}\";");
                w.WriteLine("       }\r");
            }

            #endregion

            #region 增删改

            /******** 待改善，这部分会检测数数库中的过程 ********/
            // p_tablename_save 方法
            sql = "select name,type_name(xusertype)as typename,isoutparam from syscolumns where id = object_id('" + p_saveName + "')";
            dt_proce_columns = db.ExecuteSql(sql);    // 过程的所有参数

            if (dt_proce_columns != null && dt_proce_columns.Rows.Count > 0)
            {
                fieldsname = "";
                parmname = "";
                for (int j = 0; j < dt_proce_columns.Rows.Count; j++)
                {
                    int isoutparam = 0;
                    try
                    {
                        isoutparam = Convert.ToInt32(dt_proce_columns.Rows[j]["isoutparam"].ToString());
                    }
                    catch { }

                    if (isoutparam == 0)
                    {
                        fieldsname += CUtility.SqlDataTypeToCodeType(dt_proce_columns.Rows[j]["typename"].ToString()) + " " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                        parmname += dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");

                        if (j < dt_proce_columns.Rows.Count - 1)
                        {
                            fieldsname += ",";
                        }
                    }
                    else
                    {
                        //fieldsname += "out " + CUtility.SqlDataTypeToCodeType(dt_proce_columns.Rows[j]["typename"].ToString()) + " " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                        parmname += " ref " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                    }

                    if (j < dt_proce_columns.Rows.Count - 1)
                    {                        
                        parmname += ",";
                    }
                }
                fieldsname = fieldsname.Substring(0, fieldsname.Length - 1);

                w.WriteLine("       /// <summary>");
                w.WriteLine("       /// 新增|修改");
                w.WriteLine("       /// </summary>");
                w.WriteLine("       public static string " + p_saveName + "(" + fieldsname + ")");
                w.WriteLine("       {");
                w.WriteLine("           string outmsg = \"\";");
                w.WriteLine("           int newid = 0;");             
                w.WriteLine("           " + fileName + "DAL." + p_saveName + "(" + parmname + ");");                
                w.WriteLine("           return outmsg;");
                w.WriteLine("       }\r");
            }

            // p_tablename_delete方法
            sql = "select name,type_name(xusertype)as typename, isoutparam from syscolumns where id = object_id('" + p_deleteName + "')";
            dt_proce_columns = db.ExecuteSql(sql);    // 过程的所有参数

            if (dt_proce_columns != null && dt_proce_columns.Rows.Count > 0)
            {
                fieldsname = "";
                parmname = "";
                int isoutparam = 0;
                for (int j = 0; j < dt_proce_columns.Rows.Count; j++)
                {
                    try
                    {
                        isoutparam = Convert.ToInt32(dt_proce_columns.Rows[j]["isoutparam"].ToString());
                    }
                    catch { }

                    if (isoutparam == 0)
                    {
                        fieldsname += CUtility.SqlDataTypeToCodeType(dt_proce_columns.Rows[j]["typename"].ToString()) + " " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                        parmname += dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");

                        if (j < dt_proce_columns.Rows.Count - 1)
                        {
                            fieldsname += ",";
                        }
                    }
                    else
                    {
                        //fieldsname += " out " + CUtility.SqlDataTypeToCodeType(dt_proce_columns.Rows[j]["typename"].ToString()) + " " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                        parmname += " ref " + dt_proce_columns.Rows[j]["name"].ToString().Replace("@", "");
                    }

                    if (j < dt_proce_columns.Rows.Count - 1)
                    {                        
                        parmname += ",";
                    }
                }
                fieldsname = fieldsname.Substring(0, fieldsname.Length - 1);

                w.WriteLine("       /// <summary>");
                w.WriteLine("       /// 删除数据");
                w.WriteLine("       /// </summary>");
                w.WriteLine("       public static string " + p_deleteName + "(" + fieldsname + ")");
                w.WriteLine("       {");
                w.WriteLine("           string outmsg = \"\";");                
                w.WriteLine("           " + fileName + "DAL." + p_deleteName + "(" + parmname + ");");                
                w.WriteLine("           return outmsg;");
                w.WriteLine("       }\r");
            }

            #endregion

            w.WriteLine("       #endregion");
            #endregion

            w.WriteLine("   }");
            w.WriteLine("}");

            w.Flush();
            w.Close();
        }

        return tablename + "BLL.cs生成成功";
    }

    #endregion
}

